﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace Edu.EntityFrameworkCore
{
    public class EduMigrationsDbContextFactory : IDesignTimeDbContextFactory<EduMigrationsDbContext>
    {
        public EduMigrationsDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<EduMigrationsDbContext>()
                .UseMySql(configuration.GetConnectionString("Default"));

            return new EduMigrationsDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            Console.WriteLine($"当前环境:{envName}---------------------------------------");
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile($"appsettings.{envName}.json", true);
            return builder.Build();
        }
    }
}
